/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/18 20:05
 */
package org.mechanic.fund.repository.product;

import org.mechanic.fund.domain.product.ProductStocksIndex;
import org.mechanic.fund.domain.product.ProductStocksIndexType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * 基准信息数据访问接口
 *
 * @author mechanic
 * @version 0.0.1
 */
public interface ProductStocksIndexRepository extends PagingAndSortingRepository<ProductStocksIndex, String> {

    /**
     * 返回每类基准信息最新的一条记录
     *
     * @return 每类基准信息最新的一条记录
     */
    //@Query(value = "SELECT * FROM product_stocks_index AS p, "
    //               + "(SELECT product_stocks_index_type_id, MAX(lastest_date) AS lastest_date FROM product_stocks_index GROUP BY product_stocks_index_type_id) AS pt "
    //               + "WHERE p.product_stocks_index_type_id=pt.product_stocks_index_type_id AND p.lastest_date=pt.lastest_date ORDER BY p.lastest_date DESC ", nativeQuery = true)
    @Query(value = "SELECT p FROM ProductStocksIndex p WHERE p.lastestDate IN (SELECT MAX(lastestDate) FROM ProductStocksIndex GROUP BY productStocksIndexType)")
    Page<ProductStocksIndex> findNewestByProductStocksIndexType(Pageable pageable);

    /**
     * 返回匹配指定基准信息的基准信息集合
     *
     * @param type 基准信息类型
     * @return 指定基准信息的基准信息集合
     */
    //@Query(value = "SELECT * FROM product_stocks_index p WHERE p.product_stocks_index_type_id=?1 ORDER BY p.lastest_date DESC ", nativeQuery = true)
    @Query(value = "SELECT p FROM ProductStocksIndex p WHERE p.productStocksIndexType=?1 ORDER BY p.lastestDate DESC ")
    Page<ProductStocksIndex> findByProductStocksIndexTypeId(ProductStocksIndexType type, Pageable pageable);
}
